package com.backend.teamapi.service;

import com.backend.teamapi.model.Team;
import com.backend.teamapi.model.User;
import com.backend.teamapi.repository.TeamRepository;
import com.backend.teamapi.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.util.List;
import java.util.Optional;

@Service
public class TeamService {

    @Autowired
    private TeamRepository teamRepository;

    @Autowired
    private UserRepository userRepository;

    // 创建团队
    public Team createTeam(String teamName, String description, Long creatorId) {
        // 1. 验证用户是否存在
        Optional<User> creatorOptional = userRepository.findById(creatorId);
        if (!creatorOptional.isPresent()) {
            throw new RuntimeException("用户不存在！");
        }
        User creator = creatorOptional.get();

        // 2. 创建团队对象
        Team team = new Team();
        team.setName(teamName);
        team.setDescription(description);
        team.setCreator(creator);
        team.setCreateTime(new Timestamp(System.currentTimeMillis()));

        // 3. 保存团队
        return teamRepository.save(team);
    }

    // 获取团队信息
    public Team getTeamById(Long teamId) {
        Optional<Team> team = teamRepository.findById(teamId);
        return team.orElse(null);  // 如果不存在返回 null
    }

    // 根据团队名获取团队
    public Team getTeamByName(String teamName) {
        return teamRepository.findByName(teamName);
    }

    // 获取用户创建的所有团队
    public List<Team> getTeamsByCreator(Long creatorId) {
        return teamRepository.findByCreatorId(creatorId);
    }

    // 获取用户参与的所有团队
    public List<Team> getTeamsByUser(Long userId) {
        return teamRepository.findByMembersId(userId);
    }

    // 加入团队
    public boolean addMemberToTeam(Long teamId, Long userId, Long operatorId) {
        Optional<Team> teamOptional = teamRepository.findById(teamId);
        Optional<User> userOptional = userRepository.findById(userId);
        Optional<User> operatorOptional = userRepository.findById(operatorId);

        if (teamOptional.isPresent() && userOptional.isPresent() && operatorOptional.isPresent()) {
            Team team = teamOptional.get();
            User user = userOptional.get();
            User operator = operatorOptional.get();

            // 判断用户是否已经是团队成员
            if (team.getMembers().contains(user)) {
                return false;  // 如果已经是成员，则返回 false
            }

            // 只有创建者才能增添成员
            if (operator.getId().equals(team.getCreator().getId())) {
                // 将用户添加为团队成员
                team.getMembers().add(user);
                teamRepository.save(team);  // 更新团队信息
                return true;
            } else {
                throw new RuntimeException("只有创建者可以添加成员！");
            }
        }

        return false;  // 团队或用户不存在
    }

    // 退出团队
    public boolean removeMemberFromTeam(Long teamId, Long userId, Long operatorId) {
        Optional<Team> teamOptional = teamRepository.findById(teamId);
        Optional<User> userOptional = userRepository.findById(userId);
        Optional<User> operatorOptional = userRepository.findById(operatorId);

        if (teamOptional.isPresent() && userOptional.isPresent() && operatorOptional.isPresent()) {
            Team team = teamOptional.get();
            User user = userOptional.get();
            User operator = operatorOptional.get();

            // 只有创建者可以移除成员
            if (operator.getId().equals(team.getCreator().getId())) {
                if (team.getMembers().contains(user)) {
                    team.getMembers().remove(user);  // 移除成员
                    teamRepository.save(team);  // 更新团队信息
                    return true;
                }
            } else if (operator.getId().equals(user.getId())) {
                // 普通成员只能退出自己的团队
                if (team.getMembers().contains(user)) {
                    team.getMembers().remove(user);  // 移除成员
                    teamRepository.save(team);  // 更新团队信息
                    return true;
                }
            } else {
                throw new RuntimeException("只有创建者或成员才能移除成员！");
            }
        }

        return false;  // 团队或用户不存在，或操作不合法
    }

    // 检查团队名是否已存在
    public boolean teamNameExists(String teamName) {
        return teamRepository.existsByName(teamName);
    }

    // 删除团队
    public boolean deleteTeam(Long teamId, Long operatorId) {
        Optional<Team> teamOptional = teamRepository.findById(teamId);
        Optional<User> operatorOptional = userRepository.findById(operatorId);

        if (teamOptional.isPresent() && operatorOptional.isPresent()) {
            Team team = teamOptional.get();
            User operator = operatorOptional.get();

            // 只有团队创建者才能删除团队
            if (operator.getId().equals(team.getCreator().getId())) {
                teamRepository.delete(team);  // 删除团队
                return true;
            } else {
                throw new RuntimeException("只有创建者可以删除团队！");
            }
        }

        return false;  // 团队不存在
    }
}
